package edu.ccut.saturn.tag.complex.util;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;


public final class StringHelper {
	public static final String translateFromISO(String string,
			String charsetName) throws UnsupportedEncodingException {
		if (string != null)
			return new String(string.getBytes("ISO8859-1"), charsetName);
		else
			return null;
	}

	public static final String translate(String string, String charsetOneName,
			String charsetTwoName) throws UnsupportedEncodingException {
		if (!charsetOneName.equals(charsetTwoName)) {
			if (string != null)
				return new String(string.getBytes(charsetOneName),
						charsetTwoName);
			else
				return null;
		} else {
			return string;
		}
	}

	public static final boolean isNotEmpty(String string) {
		return string != null && string.length() > 0;
	}

	public static final boolean isEmpty(String string) {
		return string == null || string.length() == 0;
	}
	
	public static final String getNotEmptyValue(String value, String defaultValue) {
		if (isEmpty(value)) {
			return defaultValue;
		}
		
		return value;
	}

	public static final String validate(String string) {
		if (string == null)
			return "";
		else
			return string;
	}

	public static final boolean isValueLegal(String string, String invalidChar) {
		int i = invalidChar.length();
		for (int j = 0; j < i; j++)
			if (!isCharValueLegal(string, invalidChar.charAt(j)))
				return false;

		return true;
	}

	private static boolean isCharValueLegal(String string, char c) {
		int i = string.length();
		for (int j = 0; j < i; j++)
			if (string.charAt(j) == c)
				return false;
		return true;
	}

	public static final String[] split(String string, String separator) {
		int i = string.length();
		int j = separator.length();
		int k = 0;
		int l;
	
		List arraylist = new ArrayList();
		for (; k < i && (l = string.indexOf(separator, k)) >= 0; k = l + j) {
			arraylist.add(string.substring(k, l));
		}

		String as[] = new String[arraylist.size()];
		return (String[]) arraylist.toArray(as);
	}

	public static final String toValidString(Object obj) {
		if (obj == null)
			return "";
		else
			return obj.toString();
	}
}
